package org.example;

import org.junit.jupiter.api.Test;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Hello world!
 *
 */
public class App
{
    public static AtomicInteger count = new AtomicInteger(0);
    static Object lock = new Object();
    public static void incr() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized(lock){
            count.addAndGet(1);
        }
    }

    /*static int n = 1000;
    public void cyclicBarrierTest() {
        int time = 0;
        while (n ==1000) {
            n =0;
            CyclicBarrier cb = new CyclicBarrier(1000);
            for(int i=0; i<1000; i++) {
                new Thread(()->{
                    try {
                        cb.await();
                        n++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("第%d次结果%d\n",++time,n);
        }
    }*/

    @Test
    public void synchronizedTest() {
        for (int i = 0; i < 1000; i++) {
            new Thread(()->App.incr()).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println( "运行结果:" + count);
    }

    @Test
    public void atomicIntegerTest() {

        for (int k = 0; k < 10; k++) {
            AtomicInteger i = new AtomicInteger(0);
            for (int j = 0; j < 1000; j++) {
                new Thread(()->{
                    i.addAndGet(1);
                },"t1").start();
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(i);
        }
    }

    @Test
    public void joinTest() throws InterruptedException {


        Thread t1 = new ThreadT("线程1");
        Thread t2 = new ThreadT("线程2");
        Thread t3 = new ThreadT("线程3");

        t1.start();
        t1.join(1);
        t2.start();
//        t2.join(  );
        t3.start();
    }
}

class ThreadT extends Thread {
    public ThreadT(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(this.getName() + " : " + i); ;
        }
    }
}
